package services;

import java.util.Collection;
import java.util.Date;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import repositories.CommentRepository;
import domain.Administrator;
import domain.AvailableItem;
import domain.Comment;
import domain.Customer;

@Service
@Transactional
public class CommentService {
	@Autowired
	private CommentRepository commentRepository;
	@Autowired
	private AvailableItemService availableItemService;

	@Autowired
	private PurchasedItemService purchasedItemService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private AdministratorService administratorService;

	public CommentService() {
		super();
	}

	public Collection<Comment> findAll() {
		Administrator principal;
		principal = administratorService.findByPrincipal();
		Assert.isTrue(principal instanceof Administrator);
		Collection<Comment> result;
		result = commentRepository.findAll();
		return result;
	}

	public Collection<Comment> findCommentsBySeller() {
		Collection<Comment> result;
		Customer seller;

		seller = customerService.findByPrincipal();
		result = commentRepository.findCommentsBySeller(seller.getId());
		return result;

	}

	public Collection<Comment> findCommentsByItemId(int availableItemId) {
		Collection<Comment> result;
		Customer principal;
		principal = customerService.findByPrincipal();
		Assert.isTrue(principal instanceof Customer);

		result = commentRepository.findCommentsByItemId(availableItemId);
		return result;

	}

	public Double findAverageRatingBySeller() {
		Double result;
		Customer seller;

		seller = customerService.findByPrincipal();
		result = 0.0;

		result = commentRepository.findAverageRatingBySeller(seller.getId());

		return result;

	}

	public Comment create(int availableItemId) {
		Comment result;
		AvailableItem availableItem;
		availableItem = availableItemService.findOne(availableItemId);

		Assert.isTrue(purchasedItemService.isBuyer(availableItem));

		result = new Comment();
		result.setCreationMoment(new Date());
		result.setAvailableItem(availableItem);
		return result;
	}

	public void save(Comment comment) {
		Assert.notNull(comment);
		AvailableItem availableItem;
		availableItem = comment.getAvailableItem();

		Assert.isTrue(!comment.getAvailableItem().getSeller()
				.equals(customerService.findByPrincipal()));
		Assert.isTrue(purchasedItemService.isBuyer(availableItem));
		Assert.isTrue(!comment.getText().isEmpty());
		Assert.isTrue(comment.getRating() >= 0);
		Assert.isTrue(comment.getRating() <= 10);

		commentRepository.save(comment);

	}

}
